package com.zbkj.crmeb.merchant.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.utils.CrmebUtil;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.SpringBeanUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.ChannelMerchantAccount;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.service.ReserveMoneyDetailService;
import com.zbkj.crmeb.enums.*;
import com.zbkj.crmeb.enums.logistics.DeliveryChannelEnum;
import com.zbkj.crmeb.export.vo.SupplierOrderExcelVo;
import com.zbkj.crmeb.express.model.Express;
import com.zbkj.crmeb.express.service.ExpressService;
import com.zbkj.crmeb.handler.orderconfirm.AbstractOrderConfirmHandler;
import com.zbkj.crmeb.handler.orderconfirm.ByOrderConfirmHandler;
import com.zbkj.crmeb.handler.orderconfirm.OrderConfirmContext;
import com.zbkj.crmeb.handler.orderconfirm.OrderConfirmInterface;
import com.zbkj.crmeb.merchant.admin.service.SupplierStoreOrderService;
import com.zbkj.crmeb.plat.enums.MerPlatEnums;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.AccountFlow;
import com.zbkj.crmeb.store.model.OrderInfoDelivery;
import com.zbkj.crmeb.store.model.PurchaseGoods;
import com.zbkj.crmeb.store.model.StoreBrand;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.request.OrderInfoDeliveryRequest;
import com.zbkj.crmeb.store.request.StoreOrderRefundRequest;
import com.zbkj.crmeb.store.request.StoreOrderSearchRequest;
import com.zbkj.crmeb.store.request.StoreOrderSendRequest;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreOrderCountItemResponse;
import com.zbkj.crmeb.store.response.StoreOrderTopItemResponse;
import com.zbkj.crmeb.store.response.SupplierInfo;
import com.zbkj.crmeb.store.response.SupplierOrderItemResponse;
import com.zbkj.crmeb.store.response.SupplierOrderResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.store.service.impl.StoreOrderServiceImpl;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.service.SystemAdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class SupplierStoreOrderServiceImpl extends ServiceImpl<StoreOrderDao, StoreOrder> implements SupplierStoreOrderService {

    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    private PurchaseGoodsService purchaseGoodsService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private OrderInfoDeliveryService orderInfoDeliveryService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private ExpressService expressService;
    @Autowired
    private StoreOrderStatusService storeOrderStatusService;
    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;
    @Autowired
    private AccountFlowService accountFlowService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private ReserveMoneyDetailService reserveMoneyDetailService;
    @Autowired
    private TencentLogisticsService tencentLogisticsService;

    @Autowired
    private StoreOrderServiceImpl storeOrderServiceImpl;

    @Qualifier("byOrderConfirmHandler")
    @Autowired
    private OrderConfirmInterface orderConfirmInterface;

    @Override
    public SupplierOrderResponse orderList(StoreOrderSearchRequest request, PageParamRequest pageParamRequest) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(request.getMerId());
        request.setIsEurope(supplierInfo.getIsEurope());
        SupplierOrderResponse response = new SupplierOrderResponse();
        //状态数量
        response.setStatus(
                new StoreOrderCountItemResponse(
                        getCount(request, Constants.ORDER_STATUS_ALL), //全部
                        null, //未支付
                        getCount(request, Constants.ORDER_STATUS_NOT_SHIPPED), //未发货
                        getCount(request, Constants.ORDER_STATUS_SPIKE), //待收货
                        getCount(request, Constants.ORDER_STATUS_COMPLETE),//交易完成
                        getCount(request, Constants.ORDER_STATUS_REFUNDING),//退款中
                        getCount(request, Constants.ORDER_STATUS_REFUNDED),//退货退款
                        null,//补偿性退款
                        getCount(request, Constants.ORDER_STATUS_CONFIRM),//待确认
                        getCount(request, Constants.ORDER_STATUS_CANCEL)//已取消
                )
        );
        //列表数据
        List<SupplierOrderItemResponse> storeOrderItemResponseArrayList = new ArrayList<>();
        StoreOrderSearchRequest searchRequest = new StoreOrderSearchRequest();
        BeanUtils.copyProperties(request,searchRequest);
        QueryWrapper<PurchaseGoods> lambdaQueryWrapper = getStoreOrderListRequest(searchRequest);
        Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        boolean flag = Objects.nonNull(supplierInfo.getCurrency()) && !supplierInfo.getCurrency().equals(CurrencyEnum.CN);
        //查询子订单
        List<PurchaseGoods> purchaseGoodsList = purchaseGoodsService.list(lambdaQueryWrapper);
        if(CollectionUtils.isNotEmpty(purchaseGoodsList)){
            storeOrderItemResponseArrayList = formatOrder(purchaseGoodsList,flag);
        }
        BigDecimal amount = BigDecimal.ZERO;
        lambdaQueryWrapper.select(flag ? "sum(ceil(goods_price/exchange_rate*100)/100) goods_price" :"sum(goods_price) goods_price");
        PurchaseGoods goodsServiceOne = purchaseGoodsService.getOne(lambdaQueryWrapper);
        if(goodsServiceOne != null){
            amount = goodsServiceOne.getGoodsPrice().setScale(2,RoundingMode.DOWN);
        }
        CommonPage<SupplierOrderItemResponse> storeOrderItemResponseCommonPage = CommonPage.restPage(CommonPage.copyPageInfo(page, storeOrderItemResponseArrayList));
        response.setList(storeOrderItemResponseCommonPage);
        //头部数据
        pageParamRequest.setLimit(1);
        response.setTop(new StoreOrderTopItemResponse(getCount(request, request.getStatus()), amount, null, null, null));
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmOrder(Integer id, Boolean status, String remark,Integer merId,String ip) {
        PurchaseGoods purchaseGoods = purchaseGoodsService.getById(id);
        StoreOrderInfo storeOrderInfo = storeOrderInfoService.getById(purchaseGoods.getStoreOrderInfoId());
        if(purchaseGoods == null){
            throw new CrmebException("该采购单不存在");
        }
        if(Objects.equals(purchaseGoods.getPushType(),9)){
            throw new CrmebException("该采购单为备份订单,请在商户后台操作");
        }
        if(!Objects.equals(purchaseGoods.getPushStatus(),"1")){
            throw new CrmebException("该采购单推送失败");
        }
        if(status && !purchaseGoods.getStatus().equals(OrderStatusEnum.CONFIRM.getCode())){
            throw new CrmebException("该采购单不是待确认状态");
        }
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        if(supplierInfo.getCreateTime().after(purchaseGoods.getCreateTime())){
            throw new CrmebException("该采购单在供应商账户创建前生成，只读状态");
        }

        if(status && !storeOrderInfo.getStatus().equals(OrderStatusEnum.CONFIRM.getCode())){
            throw new CrmebException("该采购单对应订单状态不是未确认！");
        }

        purchaseGoods.setStatus(status ? OrderStatusEnum.NOT_SHIPPED.getCode() : OrderStatusEnum.CANCEL.getCode())
                .setRefundPrice(status ? BigDecimal.ZERO : purchaseGoods.getGoodsPrice())
                .setCancelReason(status ? null : remark);
        // 备用金结算
        reserveMoneyDetailService.calcReserveMoney(purchaseGoods, supplierInfo.getCurrency(), merId, id, ip);
        boolean update = purchaseGoodsService.updateById(purchaseGoods);
        if(!update){
            return false;
        }

        String message = "";
        if(purchaseGoods.getStatus().equals(OrderStatusEnum.NOT_SHIPPED.getCode())){
//            StoreOrderInfo storeOrderInfo = storeOrderInfoService.getById(purchaseGoods.getStoreOrderInfoId());
            if(storeOrderInfo.getStatus().equals(OrderStatusEnum.CONFIRM.getCode())){
                storeOrderInfo.setStatus(OrderStatusEnum.NOT_SHIPPED.getCode());
                storeOrderInfo.setActualSupplierId(supplierInfo.getSupplierId());
                storeOrderInfo.setActualCost(purchaseGoods.getGoodsPrice());
                storeOrderInfo.setActualCostEur(priceUtil.rmb2EurStatic(purchaseGoods.getGoodsPrice(),storeOrderInfo.getExchangeRate()));
                storeOrderInfo.setActualStockAreaCode(purchaseGoods.getGoodsTempId());
                storeOrderInfoService.updateById(storeOrderInfo);
                //查询主订单状态
                StoreOrder storeOrder = getById(storeOrderInfo.getOrderId());
                if(storeOrder.getStatus().equals(OrderStatusEnum.CONFIRM.getCode())){
                    storeOrder.setStatus(OrderStatusEnum.NOT_SHIPPED.getCode());
                    updateById(storeOrder);
                }

                message="供应商:"+purchaseGoods.getGoodsSupplier()+"确认订单";
                //确认订单记录备注
                storeOrderStatusService.createLog(storeOrderInfo.getOrderId(), storeOrderInfo.getChildOrderNumber(), Constants.ORDER_CONFIRM_SUCCESS, message);
            }
        }else {
            storeOrderInfo.setStatus(OrderStatusEnum.CONFIRM.getCode());
            storeOrderInfoService.updateById(storeOrderInfo);
            purchaseGoodsService.remove(Wrappers.<PurchaseGoods>lambdaQuery().eq(PurchaseGoods::getStoreOrderInfoId,storeOrderInfo.getId()));
            //查询主订单状态
            StoreOrder storeOrder = getById(storeOrderInfo.getOrderId());
            if(!storeOrder.getStatus().equals(OrderStatusEnum.CONFIRM.getCode())){
                storeOrder.setStatus(OrderStatusEnum.CONFIRM.getCode());
                updateById(storeOrder);
            }

            BigDecimal price = purchaseGoods.getGoodsPrice();
            if(Objects.nonNull(supplierInfo.getCurrency()) && !supplierInfo.getCurrency().equals(CurrencyEnum.CN)){
                price = price.divide(purchaseGoods.getExchangeRate(), 2, RoundingMode.UP);
            }
            int adminId = systemAdminService.getAdminId();
            ChannelMerchantAccount merchant = new ChannelMerchantAccount();
            merchant.setMerId(merId);
            merchant.setAccount(price.negate());
            merchant.setFreezeAccount(price);
            channelMerchantAccountService.calcMoney(merchant);
            accountFlowService.saveAccountFlow(merId,purchaseGoods.getId(),adminId,ip,
                    AccountFlowTypeEnum.PRODUCT,price.negate(),null,null, "取消订单");

            message="供应商:"+purchaseGoods.getGoodsSupplier()+"取消订单";
            //取消订单记录备注
            storeOrderStatusService.createLog(storeOrderInfo.getOrderId(), storeOrderInfo.getChildOrderNumber(), Constants.ORDER_CANCEL_SUCCESS, message);
        }
        // 后置异步处理
        afterAsyncHandler(storeOrderInfo,purchaseGoods);
        return true;
    }

    private void afterAsyncHandler(StoreOrderInfo storeOrderInfo, PurchaseGoods purchaseGoods) {
        String merId = storeOrderInfo.getFeature("merId");
        if (StringUtils.isBlank(merId)) {
            log.error("订单确认后置任务获取不到商户号,订单号:{}", storeOrderInfo.getOrderId());
            return;
        }
        MerPlatEnums merPlatEnums = MerPlatEnums.getEnumByMerId(Integer.valueOf(merId));
        if (merPlatEnums == null) {
            throw new CrmebException("商户获取异常");
        }
        try {
            OrderConfirmInterface bean = SpringBeanUtil.getBean(merPlatEnums.getOrderHandle(), OrderConfirmInterface.class);
            OrderConfirmContext orderConfirmContext = new OrderConfirmContext(storeOrderInfo, purchaseGoods);
            CompletableFuture.runAsync(()->{
                boolean execute = bean.execute(orderConfirmContext);
            });
        } catch (Exception e) {
            throw new CrmebException("平台的处理器获取异常");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean send(StoreOrderSendRequest request) {
        try{
            if(!Objects.equals(request.getType(),"1")){
                throw new CrmebException("类型错误");
            }
            PurchaseGoods purchaseGoods = purchaseGoodsService.getById(request.getId());
            if(purchaseGoods == null){
                throw new CrmebException("该采购单不存在");
            }
            if(Objects.equals(purchaseGoods.getPushType(),9)){
                throw new CrmebException("该采购单为备份订单,请在商户后台操作");
            }
            if(purchaseGoods.getStatus() != Constants.ORDER_STATUS_H5_NOT_SHIPPED){
                throw new CrmebException("该采购单不是待发货状态");
            }
            StoreOrderInfo storeOrderInfo = storeOrderInfoService.getById(purchaseGoods.getStoreOrderInfoId());
            if(storeOrderInfo.getStatus() != Constants.ORDER_STATUS_H5_NOT_SHIPPED){
                throw new CrmebException("该平台订单不是待发货状态");
            }
            StoreOrder storeOrder = this.getById(storeOrderInfo.getOrderId());
            purchaseGoods.setStatus(Constants.ORDER_STATUS_H5_SPIKE);
            storeOrderInfo.setStatus(Constants.ORDER_STATUS_H5_SPIKE);
            if(!storeOrder.getStatus().equals(Constants.ORDER_STATUS_H5_SPIKE)){
                storeOrder.setStatus(Constants.ORDER_STATUS_H5_SPIKE);
                this.updateById(storeOrder);
            }
            purchaseGoodsService.updateById(purchaseGoods);
            storeOrderInfoService.updateById(storeOrderInfo);
            StoreCartResponse response = JSON.parseObject(storeOrderInfo.getInfo(),StoreCartResponse.class);
            //快递信息
            Express express = expressService.info(Integer.parseInt(request.getExpressId()));
            //物流信息列表
            String message = Constants.ORDER_LOG_MESSAGE_EXPRESS.replace("{storeName}",response.getProductInfo().getStoreName()).replace("{suk}",response.getProductInfo().getAttrInfo().getSuk())
                    .replace("{channel}","供应商").replace("{deliveryName}", express.getName()).replace("{deliveryCode}", request.getExpressCode());
            storeOrderStatusService.createLog(storeOrder.getId(),storeOrderInfo.getChildOrderNumber(), Constants.ORDER_LOG_EXPRESS, message);
            //新增物流信息
            OrderInfoDeliveryRequest delivery = new OrderInfoDeliveryRequest();
            delivery.setOrderInfoId(storeOrderInfo.getId());
            delivery.setDeliveryCompany(express.getName());
            delivery.setDeliveryNumber(request.getExpressCode());
            delivery.setName(request.getName());
            delivery.setDeliveryCode(express.getCode());
            delivery.setPhone(request.getPhone());
            delivery.setExpressId(Integer.parseInt(request.getExpressId()));
            delivery.setLogisticsStage(request.getLogisticsStage());
            if(!Objects.isNull(request.getLevel())){
                delivery.setLevel(request.getLevel());
            }
            delivery.setChannel(request.getChannel());
            orderInfoDeliveryService.addDelivery(delivery);

            // 小程序物流发货
            tencentLogisticsService.shipments(storeOrderInfo, storeOrder, express);

            //2023.5.17吉客云发货回传
            if(storeOrder.getOutOrderSource()==1){
                storeOrderServiceImpl.JkyDeliverGoods(storeOrder,storeOrderInfo);
            }

            return true;
        }catch (Exception e){
            //发货失败！
            throw new CrmebException(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refund(StoreOrderRefundRequest request,Integer merId,String ip) {
        if(!Objects.equals(request.getType(),1)){
            throw new CrmebException("退款状态异常");
        }
        PurchaseGoods purchaseGoods = purchaseGoodsService.getById(request.getOrderId());
        if(purchaseGoods == null){
            throw new CrmebException("该采购单不存在");
        }
        if(Objects.equals(purchaseGoods.getPushType(),9)){
            throw new CrmebException("该采购单为备份订单,请在商户后台操作");
        }
        if(purchaseGoods.getRefundStatus() != 1){
            throw new CrmebException("该采购单不是申请退款状态");
        }
        if(request.getAmount().compareTo(BigDecimal.ZERO) < 0){
            throw new CrmebException("输入金额应大于等于0");
        }
        //传入价格转换
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        boolean flag = StringUtils.isNotBlank(channelMerchant.getCurrency()) && !channelMerchant.getCurrency().equals(CurrencyEnum.CN.toString());
        BigDecimal amount = flag ? request.getAmount().multiply(purchaseGoods.getExchangeRate()).setScale(2, RoundingMode.DOWN) : request.getAmount();
        if(amount.compareTo(purchaseGoods.getGoodsPrice()) > 0){
            throw new CrmebException("退款金额大于支付金额，请修改退款金额");
        }
        purchaseGoods.setStatus(-2);
        purchaseGoods.setRefundStatus(2);
        purchaseGoods.setRefundPrice(amount);
        // 备用金结算
        reserveMoneyDetailService.calcReserveMoney(purchaseGoods, Objects.isNull(channelMerchant.getCurrency()) ? null : CurrencyEnum.valueOf(channelMerchant.getCurrency()), merId, request.getOrderId(), ip);
        purchaseGoodsService.updateById(purchaseGoods);
        int id = systemAdminService.getAdminId();
        ChannelMerchantAccount merchant = new ChannelMerchantAccount();
        merchant.setMerId(channelMerchant.getId());
        merchant.setAccount(request.getAmount().negate());
        merchant.setFreezeAccount(request.getAmount());
        channelMerchantAccountService.calcMoney(merchant);
        accountFlowService.saveAccountFlow(channelMerchant.getId(),purchaseGoods.getId(),id,ip,
                AccountFlowTypeEnum.PRODUCT,request.getAmount().negate(),null,null, "退货退款");
        return true;
    }

    @Override
    public boolean refundRefuse(Integer id,Integer merId) {
        PurchaseGoods purchaseGoods = purchaseGoodsService.getById(id);
        if(purchaseGoods == null){
            throw new CrmebException("该采购单不存在");
        }
        if(Objects.equals(purchaseGoods.getPushType(),9)){
            throw new CrmebException("该采购单为备份订单,请在商户后台操作");
        }
        if(purchaseGoods.getRefundStatus() != 1){
            throw new CrmebException("该采购单不是申请退款状态");
        }
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        purchaseGoods.setRefundStatus(0);
        purchaseGoodsService.updateById(purchaseGoods);
        StoreOrderInfo storeOrderInfo = storeOrderInfoService.getById(purchaseGoods.getStoreOrderInfoId());
        storeOrderStatusService.createLog(storeOrderInfo.getOrderId(),storeOrderInfo.getChildOrderNumber(), Constants.ORDER_SUPPLIER_LOG_REFUND, "供应商:"+supplierInfo.getSupplierName()+"拒绝退款");
        return true;
    }

    @Override
    public List<SupplierOrderExcelVo> parseExportList(List<SupplierOrderItemResponse> orderList,Integer merId) {
        List<SupplierOrderExcelVo> list = new ArrayList<>();
        for (SupplierOrderItemResponse order : orderList) {
            SupplierOrderExcelVo vo = new SupplierOrderExcelVo();
            BeanUtils.copyProperties(order,vo);
            vo.setPushTime(DateFormatUtils.format(order.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            String imgUrl = order.getGoodsImg();
            imgUrl = StringUtil.isEmpty(imgUrl) ? "" : imgUrl.substring(0, !imgUrl.contains("?") ? imgUrl.length() : imgUrl.indexOf("?"))+"?x-oss-process=image/resize,m_fill,w_100,h_100";
            vo.setImage(imgUrl);
            vo.setQuantity(1);
            vo.setOtPriceCNY(priceUtil.eur2RmbStatic(order.getGoodsOtPrice(),order.getExchangeRate()));
            vo.setOtPriceEUR(order.getGoodsOtPrice());
            vo.setPriceCNY(order.getGoodsPrice());
            vo.setPriceEUR(priceUtil.rmb2EurStatic(order.getGoodsPrice(),order.getExchangeRate()));
            vo.setTempName(StockAreaTempEnum.getByTempId(order.getTempId()).getStockAreaName());
            vo.setOrderStatus(OrderStatusEnum.valueOf(order.getStatus()).getMsg());
            vo.setRefundStatus(RefundStatusEnum.valueOf(order.getRefundStatus()).getMsg());
            if(order.getStatus().equals(OrderStatusEnum.REJECTED_SUCCESS.getCode())){
                AccountFlow flow = accountFlowService.getOne(Wrappers.<AccountFlow>lambdaQuery().eq(AccountFlow::getMerId, merId).eq(AccountFlow::getOtId, order.getId()).eq(AccountFlow::getRemark, "退货退款"));
                if(flow!= null){
                    vo.setRefundTime(DateFormatUtils.format(flow.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                    SystemAdmin systemAdmin = Optional.ofNullable(systemAdminService.getById(flow.getOperateId())).orElse(new SystemAdmin());
                    vo.setRefundOperator(systemAdmin.getRealName());
                }
            }
            List<OrderInfoDelivery> deliveryList = order.getDeliveryList();
            if(CollectionUtils.isNotEmpty(deliveryList)){
                OrderInfoDelivery delivery = deliveryList.get(0);
                vo.setDeliveryTime(DateFormatUtils.format(delivery.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                vo.setDeliveryCompany(delivery.getDeliveryCompany());
                vo.setDeliveryNumber(delivery.getDeliveryNumber());
            }
            list.add(vo);
        }
        return list;
    }

    private List<SupplierOrderItemResponse> formatOrder(List<PurchaseGoods> purchaseGoodsList,boolean flag) {
        List<Integer> orderInfoIdList = purchaseGoodsList.stream().map(PurchaseGoods::getStoreOrderInfoId).distinct().collect(Collectors.toList());
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery().in(StoreOrderInfo::getId, orderInfoIdList));
        Map<Integer, StoreOrderInfo> orderInfoMap = storeOrderInfoList.stream().collect(Collectors.toMap(StoreOrderInfo::getId, e -> e));
        List<Integer> orderIdList = storeOrderInfoList.stream().map(StoreOrderInfo::getOrderId).distinct().collect(Collectors.toList());
        List<StoreOrder> storeOrderList = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery().in(StoreOrder::getId, orderIdList));
        Map<Integer, StoreOrder> orderMap = storeOrderList.stream().collect(Collectors.toMap(StoreOrder::getId, e -> e));
        List<Integer> cateIdList = purchaseGoodsList.stream().map(PurchaseGoods::getGoodsCateId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        cateIdList.add(0);
        List<CategoryMatch> categoryMatchList = categoryMatchService.list(Wrappers.<CategoryMatch>lambdaQuery().in(CategoryMatch::getId, cateIdList).eq(CategoryMatch::getType,1));
        Map<Integer, String> cateMap = categoryMatchList.stream().collect(Collectors.toMap(CategoryMatch::getId, CategoryMatch::getName));
        List<SupplierOrderItemResponse> responseList  = new ArrayList<>();
        for (PurchaseGoods good : purchaseGoodsList) {
            SupplierOrderItemResponse response = new SupplierOrderItemResponse();
            BeanUtils.copyProperties(good,response);
            if(good.getRefundStatus() == 1){
                response.setStatus(OrderStatusEnum.APPLY_REFUND.getCode());
            }
            response.setGoodsPrice(flag ? good.getGoodsPrice().divide(good.getExchangeRate(),2,RoundingMode.UP) : good.getGoodsPrice());
            //商品货号 分类
            StoreOrderInfo storeOrderInfo = orderInfoMap.get(good.getStoreOrderInfoId());
            //有时会存在为空的情况
            if (Objects.isNull(storeOrderInfo)){
                continue;
            }
            StoreCartResponse storeCartResponse = JSON.parseObject(storeOrderInfo.getInfo(), StoreCartResponse.class);
            response.setKeyword(storeCartResponse.getProductInfo().getKeyword());
            //收货信息
            StoreOrder storeOrder = orderMap.get(storeOrderInfo.getOrderId());
            response.setAddress(storeOrderInfo.getDeliveryAddress());
            response.setUserName(storeOrder.getRealName());
            response.setUserPhone(storeOrder.getUserPhone());
            response.setIdCard(storeOrder.getIdCard());
            //物流信息
            response.setTempId(good.getGoodsTempId());
            List<OrderInfoDelivery> deliveryList = orderInfoDeliveryService.list(Wrappers.<OrderInfoDelivery>lambdaQuery().eq(OrderInfoDelivery::getChannel, DeliveryChannelEnum.SUPPLIER.getCode())
                    .eq(OrderInfoDelivery::getOrderInfoId, good.getStoreOrderInfoId()));
            response.setDeliveryList(deliveryList);
            response.setCateName(cateMap.get(good.getGoodsCateId()));
            response.setPushStoreOrderId(storeOrderInfo.getChildOrderNumber());
            response.setStoreOrderId(storeOrder.getOrderId());
            // 备注
            response.setMark(storeOrder.getMark());
            responseList.add(response);
        }
        return responseList;
    }

    private QueryWrapper<PurchaseGoods> getStoreOrderListRequest(StoreOrderSearchRequest request) {
        QueryWrapper<PurchaseGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PurchaseGoods::getChannelType,request.getIsEurope())
                .eq(PurchaseGoods::getPushStatus,1)
                .orderByDesc(PurchaseGoods::getCreateTime);
        if(StringUtils.isNotBlank(request.getDateLimit())) {
            dateLimitUtilVo dateLimitUtilVo = DateUtil.getDateLimit(request.getDateLimit());
            request.setStartTime(dateLimitUtilVo.getStartTime());
            request.setEndTime(dateLimitUtilVo.getEndTime());
        }
        if(StringUtils.isNotBlank(request.getStartTime())){
            queryWrapper.lambda().ge(PurchaseGoods::getCreateTime,request.getStartTime());
        }
        if(StringUtils.isNotBlank(request.getEndTime())){
            queryWrapper.lambda().le(PurchaseGoods::getCreateTime,request.getEndTime());
        }
        if(StringUtils.isNotBlank(request.getOrderId())){
            queryWrapper.lambda().and(qr -> qr.eq(PurchaseGoods::getChannelOrderSn,request.getOrderId())
                    .or().eq(PurchaseGoods::getStoreOrderId, request.getOrderId())
                    .or().like(PurchaseGoods::getPushStoreOrderId, request.getOrderId()));
        }
        if(StringUtils.isNotBlank(request.getBrandIdList())){
            List<String> brandIdList = Arrays.asList(request.getBrandIdList().split(","));
            List<StoreBrand> storeBrandList = storeBrandService.list(Wrappers.<StoreBrand>lambdaQuery().in(StoreBrand::getId, brandIdList).eq(StoreBrand::getType, 1));
            List<String> brandList = storeBrandList.stream().map(StoreBrand::getEnName).distinct().collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(brandList)){
                queryWrapper.lambda().in(PurchaseGoods::getGoodsBrand,brandList);
            }
        }
        if(StringUtils.isNotBlank(request.getCateIdList())){
            List<String> cateIdList = Arrays.asList(request.getCateIdList().split(","));
            queryWrapper.lambda().in(PurchaseGoods::getGoodsCateId,cateIdList);
        }
        if(request.getCommodityType() != null){
            queryWrapper.lambda().eq(PurchaseGoods::getCommodityType,request.getCommodityType());
        }
        String status = request.getStatus();
        if(null != status){
            List<Integer> orderStatusList = new ArrayList<>();
            Integer orderStatus = null; //订单状态
            Integer refundStatus = null; //退款状态
            switch (status){
                case Constants.ORDER_STATUS_ALL:
                    orderStatusList = Stream.of(1,2,4,5,6,-1,-2).collect(Collectors.toList());
                    break;
//                case Constants.ORDER_STATUS_UNPAID: //未支付
//                    orderStatus = 0;
//                    break;
                case Constants.ORDER_STATUS_NOT_SHIPPED: //未发货
                    orderStatus = 1;
                    break;
                case Constants.ORDER_STATUS_SPIKE: //待收货
                    orderStatus = 2;
                    break;
//                case Constants.ORDER_STATUS_BARGAIN: //待评价
//                    orderStatus = 3;
//                    break;
                case Constants.ORDER_STATUS_COMPLETE: //交易完成
                    orderStatus = 4;
                    break;
                case Constants.ORDER_STATUS_CANCEL: //取消
                    orderStatus = 5;
                    break;
                case Constants.ORDER_STATUS_REFUNDING: //退款中
                    refundStatus = 1;
                    break;
                case Constants.ORDER_STATUS_REFUNDED: //退货退款
                    orderStatus = -2;
                    break;
//                case Constants.ORDER_STATUS_REFUNDED_PART: //补偿性退款
//                    refundStatus = 3;
//                    break;
                case Constants.ORDER_STATUS_CONFIRM: //待确认
                    orderStatus = OrderStatusEnum.CONFIRM.getCode();
                    break;
                default:
                    orderStatus = -99;
                    break;
            }
            if(CollectionUtils.isNotEmpty(orderStatusList)){
                queryWrapper.lambda().in(PurchaseGoods::getStatus,orderStatusList);
            }
            if(orderStatus != null){
                queryWrapper.lambda().eq(PurchaseGoods::getStatus,orderStatus).ne(PurchaseGoods::getRefundStatus,1);
            }
            if(refundStatus != null){
                queryWrapper.lambda().eq(PurchaseGoods::getRefundStatus,refundStatus);
            }
        }
        //供应商/总后台采购单：新增商品筛选（商品名称/商品ID/国际编码）
        if (StringUtils.isNotBlank(request.getProductSearch())){
            queryWrapper.lambda().and(i -> i.like(PurchaseGoods::getGoodsId,request.getProductSearch())
                    .or().like(PurchaseGoods::getGoodsName,request.getProductSearch())
                    .or().like(PurchaseGoods::getGoodKeyword,request.getProductSearch()));
        }
        // 发货时间
        if (StringUtils.isNotBlank(request.getOrderDeliveryTimeStart()) && StringUtils.isNotBlank(request.getOrderDeliveryTimeEnd())){
            queryWrapper.exists("select 1 from eb_order_info_delivery where " +
                    "eb_order_info_delivery.order_info_id = eb_purchase_goods.store_order_info_id " +
                    "and eb_order_info_delivery.update_time between '"+request.getOrderDeliveryTimeStart()+"' and '"+request.getOrderDeliveryTimeEnd()+"'");
        }

        return queryWrapper;
    }

    private Integer getCount(StoreOrderSearchRequest request, String status) {
        StoreOrderSearchRequest searchRequest = new StoreOrderSearchRequest();
        BeanUtils.copyProperties(request,searchRequest);
        searchRequest.setStatus(status);
        QueryWrapper<PurchaseGoods> lambdaQueryWrapper = getStoreOrderListRequest(searchRequest);
        return purchaseGoodsService.count(lambdaQueryWrapper);
    }

}

